package com.example.photoview;

//import com.sun.jna.platform.FileUtils;

import com.sun.jna.platform.FileUtils;
import javafx.scene.control.Alert;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;

import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;
import net.coobird.thumbnailator.Thumbnails;
public class SelectedModel {
    private static HomeController homeController=(HomeController) ControllerUtil.controllers.get(HomeController.class.getSimpleName());
    private static Path sourcePath;//源文件夹地址
    private static ArrayList<Path> sourcePathList=new ArrayList<>();
    private static Path targetPath;//目的文件夹地址
    /**
     * 选择复制或剪切 0-->复制 1-->剪切
     */
    private static int copyOrMove=-1;//选择复制或剪切 0-->复制 1-->剪切
    private static int singleOrMultiple=-1;//选择单选/多选 0-->单选  1-->多选
    private static int waitingPasteNum=0;
    private static int havePastedNum=0;
    private static int coverImage=0;
    private static String startNum;
    private static String lengthOfNum;
    public static Path getSourcePath() {
        return sourcePath;
    }

    public static ArrayList<Path> getSourcePathList() {
        return sourcePathList;
    }

    public static Path getTargetPath() {
        return targetPath;
    }

    public static int getCopyOrMove() {
        return copyOrMove;
    }

    public static int getCoverImage() {
        return coverImage;
    }

    public static int getHavePastedNum() {
        return havePastedNum;
    }

    public static int getSingleOrMultiple() {
        return singleOrMultiple;
    }

    public static int getWaitingPasteNum() {
        return waitingPasteNum;
    }

    public static void setCopyOrMove(int copyOrMove) {
        SelectedModel.copyOrMove = copyOrMove;
    }

    public static void setCoverImage(int coverImage) {
        SelectedModel.coverImage = coverImage;
    }

    public static void setHavePastedNum(int havePassedNum) {
        SelectedModel.havePastedNum = havePassedNum;
    }

    public static void setSingleOrMultiple(int singleOrMultiple) {
        SelectedModel.singleOrMultiple = singleOrMultiple;
    }

    public static void setSourcePath(Path sourcePath) {
        SelectedModel.sourcePath = sourcePath;
    }

    public static void setSourcePathList(ArrayList<Path> sourcePathList) {
        SelectedModel.sourcePathList = sourcePathList;
    }

    public static void setTargetPath(Path targetPath) {
        SelectedModel.targetPath = targetPath;
    }

    public static void setWaitingPasteNum(int waitingPasteNum) {
        SelectedModel.waitingPasteNum = waitingPasteNum;
    }

    public static boolean setSourcePath(ImageModel im){
        sourcePath=im.getImageFile().toPath();
        singleOrMultiple=0;
        return true;
    }

    /**
     * 单选时 传入一张图片地址 同时singleOrMultiple=0
     */
    public static boolean setSourcePath(String imagePath) {
        sourcePath = new File(imagePath).toPath();
        singleOrMultiple = 0;
        return true;
    }

    /**
     * 多选时直接传入一个列表即可 同时singleOrMultiple=1
     */
    public static boolean setSourcePath(ArrayList<ImageModel> imList) {
        sourcePathList.clear();    // 每次点击都需要清空List, 不创建对象以节约空间与时间
        for (ImageModel im : imList) {
            System.out.println("setSourcePath is started");
            setSourcePath(im);
            sourcePathList.add(sourcePath);
        }
        System.out.println("sourcePathList.size()="+sourcePathList.size());
        singleOrMultiple = 1;
        return true;
    }
    /**
     * 3.重命名选项 重复命名直接覆盖
     * 点击完成按钮之后执行第二部分
     */
    public static boolean renameImage(String newName) {
        /**
         * 单选
         */
        //System.out.println("sourcePathList.size()="+sourcePathList.size());
        if (singleOrMultiple == 0 ) {
            System.out.println("single");
            try {
                microRename(newName);
            } catch (IOException e) {
                System.err.println("重命名失败");
                return false;
            }
        } else if (singleOrMultiple == 1) {
            /**
             * 多选
             */
            //homeController.getStartNum()--int
            //homeController.getLengthNum()--String
            System.out.println("homeController.getStartNum()"+homeController.getStartNum());
            System.out.println("sourcePathList.size()"+sourcePathList.size());//0
            Path[] imArr = new Path[sourcePathList.size()];
            sourcePathList.toArray(imArr);
            int j=imArr.length + homeController.getStartNum();
            System.out.println("imArr.length + homeController.getStartNum()"+j);
            //没进来
            for (int i = homeController.getStartNum() ; i < j ; i++) {
                System.out.println("started:"+i);
                sourcePath = imArr[i-homeController.getStartNum()];
                String alterName;
                try {
                    String beforeName = newName.substring(0, newName.lastIndexOf("."));//前面部分保留//err是因为没有后缀.
                    String afterName = newName.substring(newName.lastIndexOf("."));//改名部分
                    String resi=beforeName + String.format("_%0"+homeController.getLengthNum()+"d", i) + afterName;
                    microRename(resi);
                }catch(StringIndexOutOfBoundsException e){
                    alterName = newName+".bmp";
                    String beforeName = alterName.substring(0, alterName.lastIndexOf("."));//前面部分保留//err是因为没有后缀.
                    String afterName = alterName.substring(alterName.lastIndexOf("."));//改名部分
                    String resi=beforeName + String.format("_%0"+homeController.getLengthNum()+"d", i) + afterName;
                    try {
                        microRename(resi);
                    }catch (Exception e2){
                         alertFailure();
                         return false;
                    }
                }
                catch (IOException e) {
                    alertFailure();
                    return false;
                }
            }
        }//end
        singleOrMultiple = -1;
        return true;
    }

    private static void alertFailure(){
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.titleProperty().set("错误信息");
        alert.headerTextProperty().set("重命名失败");
        alert.showAndWait();

    }
    private static void microRename(String newName) throws IOException {
        targetPath = new File(otherName(newName)).toPath();
     Files.move(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);
    }
    public static int compressImage(int desize) {
        if(singleOrMultiple==0){
            try{
                if(!microCompress(desize))
                    return 0;
            }catch(IOException e){
                Alert alert=new Alert(Alert.AlertType.ERROR);
                alert.setTitle("压缩错误");
                alert.setHeaderText(null);
                alert.setContentText("压缩失败");
                return 0;
            }
            return  1;
        }else if(singleOrMultiple==1){
            int success=0;
            for(Path p:sourcePathList){
                sourcePath=p;
                try{
                    if(microCompress(desize))
                        success++;
                }catch (IOException e){
                    Alert alert=new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("压缩错误");
                    alert.setHeaderText(null);
                    alert.setContentText("压缩失败");
                    return 0;
                }
            }
            return success;
        }
        singleOrMultiple=-1;
        return 0;
    }

    public static  boolean microCompress(int desSize)throws IOException{
        byte[] imageBytes=Model.getByteByFile(sourcePath.toFile());
        if(imageBytes==null||imageBytes.length<desSize*1024){
            return false;
        }
        double accuracy=0;//分辨度
        if(imageBytes.length>desSize*1024){
            accuracy=getAccuracy(imageBytes.length/1024.0);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(imageBytes.length);
            Thumbnails.of(sourcePath.toFile())
                    .scale(accuracy)  // 分辨率
                    .outputQuality(accuracy)  // 图片质量
                    .toOutputStream(bos);
            imageBytes = bos.toByteArray();
        }
        String newImagePath = suffixName(getBeforePath(), "_pview");
        File newFile = new File(newImagePath);
        return Model.getFileByByte(imageBytes, newFile);
    }
    private static double getAccuracy(double imageSize) {
        double accuracy = 0;
        if (imageSize < 1024 * 2) {
            accuracy = 0.71;
        } else if (imageSize < 1024 * 4) {
            accuracy = 0.66;
        } else if (imageSize < 1024 * 8) {
            accuracy = 0.61;
        } else {
            accuracy = 0.59;
        }
        return accuracy;
    }
    // 修改路径 复制/剪切

    private static String otherPath(String newPath) {
        StringBuilder sb = new StringBuilder(32);
        sb.append(checkPath(newPath)).append(sourcePath.getFileName().toString()); // 获得文件名
        return sb.toString();
    }
    // 修改名字 重命名
    private static String otherName(String newName) {
        StringBuilder sb = new StringBuilder(32);
        String path = sourcePath.toString().substring(0, sourcePath.toString().lastIndexOf("\\"));//把前面的保留后面的替换掉
        sb.append(path).append("\\").append(newName);//字符串连接
        return sb.toString();
    }
    // 获得图片绝对路径的前部分
    private static String getBeforePath() {
        String path = sourcePath.toString();
        return path.substring(0, path.lastIndexOf("\\"));
    }
    // 检查路径后缀
    private static String checkPath(String path) {
        StringBuilder sb = new StringBuilder(32);
        if (!path.endsWith("\\")) {
            sb.append(path).append("\\");
        } else {
            sb.append(path);
        }
        return sb.toString();
    }
    // 分割.jpg后缀 处理名字前半部分冲突
    private static String suffixName(String newPath, String suffix) {
        StringBuilder sb = new StringBuilder(32);
        String sourceName = sourcePath.getFileName().toString();
        String nameBefore = sourceName.substring(0, sourceName.indexOf(".")); // 只有一个名字 没有.
        String nameAfter = sourceName.substring(sourceName.indexOf(".")); // 带有. .jpg
        sb.append(checkPath(newPath)).append(nameBefore).append(suffix).append(nameAfter);
        return sb.toString();
    }

    /**
     * 粘贴操作，分为复制的粘贴和剪切的粘贴
     * 1、复制:要判断目标文件夹是否为当前文件夹，是则创建副本，不是则用Files.copy进行复制
     * 2、剪切：如果目标文件夹有相同的文件则覆盖掉
     * @param path
     * @return
     * @throws IOException
     */
    public static void paste(String path) throws IOException {
        havePastedNum=0;
        coverImage=0;
        //单选时,粘贴单个图片
        if (singleOrMultiple==0){
            pasteImage(path);
        }else if(singleOrMultiple==1){//多选时循环粘贴列表里的图片
            //System.out.println("abcccc");
            for (Path o:sourcePathList){
                sourcePath=o;
                System.out.println(o);
                System.out.println("oooo");
                pasteImage(path);
                System.out.println("ooo");
            }

        }


    }

    private static boolean imageRepeat(String path) {
        String targetImageName = targetPath.getFileName().toString();
        try {
            if (SearchImgModel.accurateSearch(targetImageName, Objects.requireNonNull(ImageList.initImageList(path))) != null) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    public static  void pasteImage(String path) throws IOException {

        if (copyOrMove==0){
            /*
            如果目标文件夹就是当前文件夹，就粘贴并且重命名，
            在新文件后面加“-副本”
             */
            if (getBeforePath().equals(path)){
                System.out.println("aaa");
                boolean isExist =true;
                String[] fileList = new File(path).list();
                for (String strings:fileList){
                    if (sourcePath.getFileName().toString().equals(strings)&& isExist){
                        targetPath =new File(suffixName(path,"-副本")).toPath();
                       isExist=false;
                    }
                }
                if (isExist){
                    targetPath =new File(otherPath(path)).toPath();
                }
                Files.copy(sourcePath, targetPath);// targetPath是null
                havePastedNum++;
            }else{//目标文件夹不是源文件夹
                targetPath=new File(otherPath(path)).toPath();
                if (!imageRepeat(path)){
                    Files.copy(sourcePath,targetPath);
                    havePastedNum++;
                }else{
                    //弹出窗口
                }

            }
//            HomeController homeController=(HomeController) ControllerUtil.controllers.get(HomeController.class.getSimpleName());
//            homeController.refreshImagesList(homeController.getSortComboBox().getValue());
        }else if(copyOrMove==1){
            System.out.println("waitingPasteNum  "+waitingPasteNum);
            System.out.println("havePastedNum   "+havePastedNum);
            targetPath = new File(otherPath(path)).toPath();
            if (imageRepeat(path))
                coverImage++;
            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            havePastedNum++;
            System.out.println("havePastedNum after  "+havePastedNum);
            if (havePastedNum == waitingPasteNum){
                System.out.println("abc");
                copyOrMove = -1;
            }
//           HomeController homeController=(HomeController) ControllerUtil.controllers.get(HomeController.class.getSimpleName());
//           homeController.refreshImagesList(homeController.getSortComboBox().getValue());
        }

    }

    /**实际删除功能
     * 后续使用删除微操作
     * @return
     */
   public static int deleteImage() {
        int success = 0;
        // 删除图片文件进入回收站，不直接删除
        if (singleOrMultiple == 0) {
            try {
                microDelete();
                success++;
            } catch (IOException e) {
                System.err.println("删除失败");
                return 0;
            }
        } else if (singleOrMultiple == 1) {
            for (Path p : sourcePathList) {
                sourcePath = p;
                try {
                    microDelete();
                    success++;

                } catch (IOException e) {
                    System.err.println("删除失败");
                    return 0;
                }
            }
        }
       System.out.println("delete function succeed.");
        singleOrMultiple = -1;
        return success;
    }

    /**删除的微操作
     * 调用FileUtils类 删除图片功能
     * @throws IOException
     */
    private static void microDelete() throws IOException {
       FileUtils fileUtils = FileUtils.getInstance();
        if (fileUtils.hasTrash()) {
            System.out.println("microDelete function start");
           fileUtils.moveToTrash(new File[]{(sourcePath.toFile())});//移向回收站
//            HomeController homeController=new HomeController();
//            flowPane.getChildren().remove(sourcePath.toFile());
       }

   }

}//pane.value remove


